<?php

function bLength($a){
	if (!$a)
		return 0;
	$b = preg_replace("/[\x{4e00}-\x{9fa5}]+/u",'', $a);
	$charlen = strlen($b);
	preg_match_all("#[\x{4e00}-\x{9fa5}]+#u", $a, $b);
	return $charlen + ($b[0] ? mb_strlen(join($b[0],''), 'UTF8') * 2 : 0);
}

function weiboCount($b){
	$b = str_replace("\r\n", "\n", $b);
	$c = 41; $d = 140; $e = 20; $f = $b; $h = 0;
	preg_match_all("/http:\/\/[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-A-Z0-9a-z_\$\.\+\!\*\(\)\/,:;@&=\?\~\#\%]*)*/i",$b, $g);
	if($g[0]){
		foreach($g[0] as $url){
			if (preg_match("/^(http:\/\/t\.cn)/", $url)){
				continue;
			}
			$k = bLength($url);
			preg_match("/^(http:\/\/)+(t\.sina\.com\.cn|t\.sina\.cn)/", $url) || preg_match("/^(http:\/\/)+(weibo\.com|weibo\.cn)/", $url) ? $h += $k <= $c ? $k : $k <= $d ? $e : $k - $d + $e : $h += $k <= $d ? $e : $k - $d + $e;
			$f = str_replace($url,'', $f);
		}
	}
	$l = ceil(($h + bLength($f)) / 2);
	return $l;
}


$str = 'this is a test   http://git.oschina.net/tommy/weibo-140-words-for-javascript-and-php.git end of the str!';
echo weiboCount($b);